<div class="panel panel-default">
    <div class="panel-heading">
        搜索条件
    </div>
    <div class="panel-body">
        <div class="form-group">
            <div class="row">
                <div class="col-md-2">课程代码:</div>
                <div class="col-md-2">
                    <input type="text" name="CourseCode" id="CourseCode"
                           class="form-control">
                </div>
                <div class="col-md-2">课程名称:</div>
                <div class="col-md-2">
                    <input type="text" name="CourseName" id="CourseName"
                           class="form-control">
                </div>
                <div class="col-md-3">
                    <input type="button" value="搜索" class="btn btn-info" id="btnSearch">
                    <input type="button" value="返回" class="btn btn-normal" id="btnBack" onclick="location.href='{:U('Training/index','','')}'">
                </div>

            </div>
        </div>
    </div>
</div>
<div class="panel panel-default">
    <div class="panel-body">
        <table id="list" class="table table-striped table-bordered" cellspacing="0" width="100%">
            <thead>
            <tr>
                <th></th>
                <th>课程代码</th>
                <th>课程名称</th>
                <th>课程地址</th>
                <th>试听地址</th>
                <th>学时</th>
                <th>学费</th>
                <th>是否开放</th>
                <th>是否必修</th>
            </tr>
            </thead>

            <tbody>

            </tbody>
        </table>
        <div class="col-md-offset-5">
            <button id="btnSave" name="btnSave" class="btn btn-info"> 保存关联</button>
            <input type="hidden" name="TrainingID" id="TrainingID" value="{$id}">
            (仅保存当页数据，翻页后数据无法保存)
        </div>
    </div>
</div>

<script>
    $(function () {

        $('#list').dataTable({
            "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]], //分页控制
            "pageLength": 10,//首次加载的数据条数
            "order": [[2, "desc"]],   //默认排序
            "createdRow": function (row, data, index) {
                //row 行对象,data 数据对象,index行索引
                if (data['isopenselection'] == 1) {
                    $('td', row).eq(6).css('font-weight', "bold");
                }
                if (data['IsSelected'] == 1) {
                    $('td', row).eq(0).find("input").prop("checked", true);
                }
                if (data['IsRequired'] == 1) {
                    $('td', row).eq(8).find("input").prop("checked", true);
                }

                $('td', row).eq(0).find("input[type=hidden]").val(data['IsSelected']);
            },
            "dom": '<"top"l>rt<"bottom"ip><"clear">',
            "columnDefs": [
                // 增加一列，包括删除和修改，同时将需要传递的数据传递到链接中
                {
                    "targets": [0], // 目标列位置，下标从0开始
                    "searchable": false,
                    "orderable": false,
                    "data": "id", // 数据列名
                    "render": function (data, type, full) { // 返回自定义内容
                        return "<input type='checkbox' id='ck_Selected_" + data + "' value='1'><input type='hidden' id='hd_Selected_" + data + "' value='0'>";
                    }
                },
                // 增加一列，包括删除和修改，同时将需要传递的数据传递到链接中
                {
                    "targets": [8], // 目标列位置，下标从0开始
                    "searchable": false,
                    "orderable": false,
                    "data": "id", // 数据列名
                    "render": function (data, type, full) { // 返回自定义内容
                        return "<input type='checkbox' id='ck_Required_" + data + "' value='1'>";
                    }
                }
            ],
            "language": {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 条记录",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 条记录，共 _TOTAL_ 条",
                "sInfoEmpty": "显示第 0 至 0 条记录，共 0 条",
                "sInfoFiltered": "(由 _MAX_ 条结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "processing": true,//分页，取数据等等的都放到服务端去
            "serverSide": true,//载入数据的时候是否显示“载入中”
            "columns": [
                {},
                {"data": "coursecode"},
                {"data": "coursename"},
                {"data": "courseurl"},
                {"data": "democourseurl"},
                {"data": "coursehours"},
                {"data": "coursefee"},
                {"data": "IsOpenSectionDesc"},
                {}
            ],
            "ajax": {
                "url": "{:U('Training/GetRelationData','','')}?id={$id}",
                "type": "post"
            },
        });
    });

    //搜索按钮
    $("#btnSearch").on('click', function () {
        var courseName = $("#CourseName").val();
        var courseCode = $("#CourseCode").val();

        $('#list').DataTable().column(1).search(courseCode)
                .column(2).search(courseName).draw();
    });

    //保存按钮
    $("#btnSave").on("click", function () {
        //保存数组
        var array = new Array();
        //遍历所有课程勾选
        $("input[type='checkbox'][id*='ck_Selected']").each(function () {
            var id = parseInt($(this).prop("id").split('_')[2]);
            //最新是否选中
            var isSelected = $(this).prop("checked") ? 1 : 0;
            //历史是否选中
            var before = parseInt($("input[type='hidden'][id*='hd_Selected_" + id + "']").val());
            //获取必修课勾选
            var isRequired = $("input[type='checkbox'][id*='ck_Required_" + id + "']").prop("checked") ? 1 : 0;
            array.push({
                ScormID: id,
                IsRequired: isRequired,
                IsSelected: isSelected,
                Before: before
            });
        });
        //console.log(array);
        $.ajax({
            async: false,
            url: "{:U('Training/SaveRelation','','')}",
            type: "post",
            data: {
                "data": array,
                'TrainingID' : $("#TrainingID").val()
            },
            dataType: "json",
            success: function (data) {
                alert('保存成功');
                $("#btnSearch").click();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

            }
        });
    })
</script>